package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.dongdongshop.mapper.TbUserMapper;
import com.dongdongshop.pojo.seller.TbSeller;
import com.dongdongshop.pojo.user.TbUser;
import com.dongdongshop.pojo.user.TbUserExample;
import com.dongdongshop.service.UserServiceI;
import com.dongdongshop.util.JavaMailUtils;
import com.dongdongshop.util.JobBirExecute;
import com.dongdongshop.util.JobExecute;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.mapping.TextScore;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
@Service
public class UserServiceImpl implements UserServiceI {

    @Resource
    private TbUserMapper userMapper;

    @Resource
    private JavaMailUtils javaMailUtils;

    @Resource
    private RocketMQTemplate rocketMQTemplate;




    @Override
    public void resetPassword(String username, String salt, String md5) {
        userMapper.resetPassword(username,salt,md5);
    }

    //发送邮箱
    @Override
    public void sendEmail(String email, String code) {
        javaMailUtils.sendSimpleMail(email,"重置密码",code);
    }

    @Override
    public int insertUser(TbUser user) {
        user.setBirthday(new Date());
        user.setEmail("2687996194@qq.com");
        user.setStatus("Y");
        System.out.println("邮箱"+user.getEmail());
        System.out.println("生日"+user.getBirthday());
        return userMapper.insertSelective(user);

      /*  try {
            getQuartz(user.getEmail());
            getBirthdays(user.getBirthday(),user.getPhone());
            return 1;
        }catch (Exception e){
            return 0;
        }*/
    }

    @Scheduled(cron = "0 30 12 * * ?")
    public void getQuartz() throws ParseException {
        LocalDate now = LocalDate.now();
        //减15天 查询十五天前的信息
        LocalDate localDate = now.plusDays(-15);
        String times=localDate+"";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = sdf.parse(times);
        System.out.println("时间"+parse);
        List<TbUser> userList=userMapper.findThankUser(parse);
        if (userList.size()>0){
            for (TbUser user : userList) {
                javaMailUtils.sendSimpleMail(user.getEmail(),"感谢信","感谢1111");
            }
        }
    }

    @Scheduled(cron = " 0 15 8 * * ?")
    public void getBirthdays(){
        //生成4位数的手机验证码
        String code = RandomStringUtils.randomNumeric(4);
        //给用户发送邮箱贺卡
        LocalDate now = LocalDate.now();
        int monthValue = now.getMonthValue();//月
        int dayOfMonth = now.getDayOfMonth();//日
        List<TbUser> userList=userMapper.findBirthdayByUser(monthValue,dayOfMonth);
        if (userList.size()>0){
            for (TbUser user : userList) {
                String phoneByCode=""+user.getPhone()+","+code+"";
                rocketMQTemplate.convertAndSend("sms_code",phoneByCode);
                System.out.println(new Date() + " : 定时任务执行...");
            }
        }
 //       System.err.println("Instance " + key + " of DumbJob says: " + name );
        System.out.println(new Date() + " : 定时任务结束...");
    }

   /* public  void getBirthdays(Date birthday,String phone) throws SchedulerException {
        // 根据name和group获取当前trigger身份
        TriggerKey triggerKey = TriggerKey.triggerKey("trigger25", "jobGroup25");
        CronTrigger cronTrigger = null;

        // 获取触发器的信息
        // 1、创建调度器Scheduler
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();
        try {
            cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

        // 2、创建JobDetail实例，并与JobTest类绑定(Job执行内容)
        JobDetail jobDetail = JobBuilder.newJob(JobBirExecute.class)
                .usingJobData("name", phone)
                .withIdentity("job25", "jobGroup25")
                .build();

        int month  = (birthday.getMonth())+1;
        int day = birthday.getDay();
        // 3、构建Trigger实例
        Trigger trigger = TriggerBuilder.newTrigger()
                .usingJobData("trigger25", "缓存更新触发")
                .withIdentity("trigger25", "jobGroup25")
                .withSchedule(CronScheduleBuilder.cronSchedule("0 0 0 "+ day +" "+ month +" ?"))
                .build();

        //执行任务
        scheduler.scheduleJob(jobDetail,trigger);
    }

    public void getQuartz(String email) throws SchedulerException {
        // 根据name和group获取当前trigger身份
        TriggerKey triggerKey = TriggerKey.triggerKey("trigger24", "jobGroup24");
        CronTrigger cronTrigger = null;

        // 获取触发器的信息
        // 1、创建调度器Scheduler
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();
        try {
            cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

            // 2、创建JobDetail实例，并与JobTest类绑定(Job执行内容)
            JobDetail jobDetail = JobBuilder.newJob(JobExecute.class)
                    .usingJobData("name", "感谢信")
                    .usingJobData("desc", email)
                    .withIdentity("job24", "jobGroup24")
                    .build();

        int dayOfMonth= LocalDate.now().plusDays(15).getDayOfMonth();
            // 3、构建Trigger实例
            Trigger trigger = TriggerBuilder.newTrigger()
                    .usingJobData("trigger24", "缓存更新触发")
                    .withIdentity("trigger24", "jobGroup24")
                    .withSchedule(CronScheduleBuilder.cronSchedule("0 30 12 " +dayOfMonth+" * ?"))
                    .build();

            //执行任务
         scheduler.scheduleJob(jobDetail,trigger);
    }
*/
    @Override
    public List<TbUser> getUserName(String username) {
        TbUserExample example=new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        return userMapper.selectByExample(example);
    }

    @Override
    public TbUser findName(String username) {
        return userMapper.findName(username);
    }
}
